package main

import (
	"fmt"
	"github.com/json-iterator/go"
	"info/util"
	"net/http"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

type ProducersLookupResponse struct {
	Producers []ProducerNode `json:"producers"`
}

type ProducerNode struct {
	RemoteAddress    string   `json:"remote_address"`
	Hostname         string   `json:"hostname"`
	BroadcastAddress string   `json:"broadcast_address"`
	TcpPort          int      `json:"tcp_port"`
	HttpPort         int      `json:"http_port"`
	Version          string   `json:"version"`
	Tombstones       []bool   `json:"tombstones"`
	Topics           []string `json:"topics"`
}

func findNode(topic string) (*ProducerNode, error) {
	resp, er := http.Get(lookupAddrHttp + "/nodes")
	if er != nil {
		return nil, er
	}
	var response = ProducersLookupResponse{Producers: make([]ProducerNode, 0, 1)}
	er = util.FromJsonReader(resp.Body, &response)
	if er != nil {
		fmt.Println(er)
		return nil, er
	}

	var pn *ProducerNode
	for i, n := range response.Producers {
		fmt.Println(i, n, )
		for i, t := range n.Topics {
			fmt.Println(i, t, )
			if t == topic && n.Tombstones[i] {
				continue
			}
			if nil == pn || len(n.Topics) < len(pn.Topics) {
				pn = &n
			}
		}
	}

	return pn, nil
}

func send() {

}

var lookupAddrHttp = "http://127.0.0.1:4161"

func main() {
	n, er := findNode("jjj")
	if er != nil {
		panic(er)
	}
	fmt.Println(n)
}
